# -*- coding: utf8 -*-
from tool import validate_longitude_or_latitude_format
from tool import transform_longitude_or_latitude_into_float
from grid_encoding_level_n import grid_encoding_function


def beidou_grid_code_point(longitude:str, latitude:str, level_n:int) -> dict[str, str]:
    """
    地球表面北斗二维网格的划分原点在赤道面与本初子午面的交点处，地球表面非两级区域（南纬 88度 ~ 北纬 88度）
    :param longitude: str ; 经度字符串表示
    :param latitude: str ; 纬度字符串表示
    :param level_n: int ; 网格剖分的层级
    :return: str ; 北斗网格编码
    """
    # 将经纬度转化为标准格式化形式
    try:
        longitude_format = validate_longitude_or_latitude_format(longitude)
        latitude_format = validate_longitude_or_latitude_format(latitude)
    except:
        # raise
        # 经度和纬度格式存在问题，需要验证
        return {'error':'longitude or latitude format error'}
    else:
        # 将经纬度转化为精确分数
        longitude_float = transform_longitude_or_latitude_into_float(longitude_format)
        latitude_float = transform_longitude_or_latitude_into_float(latitude_format)
        # 获取响应的网格编码函数
        grid_function = grid_encoding_function.get(level_n)
        grid_code = grid_function(longitude_float,latitude_float)
        return {'succeed':'true','grid_code':grid_code,'longitude':longitude,'latitude':latitude}


if __name__ == '__main__':
    # 经度 - x 轴 东经
    longitude = 'E116°18′45.37″'
    # 维度 - y 轴 北半球
    latitude = 'N39°59′35.38″'
    level_n = 10
    print(beidou_grid_code_point(longitude, latitude, level_n))
    # 性能测试
    from timeit import timeit
    iter_number = 1000
    duration = timeit(lambda: beidou_grid_code_point(longitude, latitude, level_n), number=iter_number)
    print('generate grid code,iter number {},cost time is {} seconds'.format(iter_number, duration))
    # generate grid code,iter number 1000,cost time is 0.03149020001851022 seconds
